package com.zzyl.nursing.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信通用接口实现
 *
 * @author I:P Masquerenaʚїɞ
 * @date 2025/6/9
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 获取openid时向微信发送的地址
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    //获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号的地址
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    /**
     * 获取openid
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> paramMap = getAppConfig();
        paramMap.put("js_code", code);

        String result = HttpUtil.get(REQUEST_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //正常情况下微信返回的时候是没有errcode和errmsg，只有在发生错误时才会有这两个属性
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    /**
     * 封装公共参数
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    private Map<String, Object> getAppConfig() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        return map;
    }

    /**
     * 获取手机号
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    @Override
    public String getPhone(String detailCode) {
        String accessToken = getToken();
        String url = PHONE_REQUEST_URL + accessToken;

        HashMap<String, Object> paramMap = new HashMap<>() {{
            put("code", detailCode);
        }};

        //JSONUtil.toJsonStr(paramMap):将map集合转成json字符串
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //errcode为0时表示返回正常
        if(jsonObject.getInt("errcode") != 0){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取access_token
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    public String getToken() {
        String token = HttpUtil.get(TOKEN_URL, getAppConfig());
        JSONObject jsonObject = JSONUtil.parseObj(token);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
